$(function () {
    'use strict';
    var linkSave = $('<span/>')
    	.attr('id', 'savefielupload')
        .prop('disabled', true)
        .text('Lưu thay đổi')
        .on('click', function () {
            var $this = $(this),
                data = $this.data();
            $this
                .off('click')
                .on('click', function () {
                	saveAvatar();
                });
            data.submit().always(function () {
            	saveAvatar();
            });
        });
    $('#setfielupload').click(function(){
    	$('#fileupload').click();
    });
    $('#cancelfielupload').click(function(){
    	backAvatar();
    });
    function backAvatar() {
    	$('#savefielupload').remove();
    	$('#cancelfielupload').hide();
		$('#setfielupload').show();
		$('#avatar-now').show();
		$('#avatar-show div').remove();
    }
    function saveAvatar () {
    	$('#savefielupload').remove();
    	$('#cancelfielupload').hide();
		$('#setfielupload').show();
		$('#avatar-now').remove();
    }
    $('#fileupload').fileupload({
        url: url,
        dataType: 'json',
        autoUpload: false,
        acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
        maxNumberOfFiles : 1,
        maxFileSize: 5000000, // 5 MB
        // Enable image resizing, except for Android and Opera,
        // which actually support image resizing, but fail to
        // send Blob objects via XHR requests:
        disableImageResize: /Android(?!.*Chrome)|Opera/
            .test(window.navigator.userAgent),
        previewMaxWidth: 120,
        previewMaxHeight: 168,
        previewCrop: false
    }).on('fileuploadadd', function (e, data) { 	
		$('#cancelfielupload').show();
		$('#setfielupload').hide();
		$('#avatar-now').hide();
    	
    	$('#avatar-show').prepend('<div/>');
    	data.context = $('#avatar-show');
        $.each(data.files, function (index, file){
        	$('.change-avatar').prepend(linkSave.clone(true).data(data));
        });
        
       
    }).on('fileuploadprocessalways', function (e, data) {
        var index = data.index,
            file = data.files[index],
            node = $(data.context.children()[index]);
        if (file.preview) {
            node.prepend(file.preview);
        }
        if (file.error) {
        	backAvatar();
        	alert(file.error);
        }
        if (index + 1 === data.files.length) {
            data.context.find('button')
                .text('Upload')
                .prop('disabled', !!data.files.error);
        }
    }).prop('disabled', !$.support.fileInput)
        .parent().addClass($.support.fileInput ? undefined : 'disabled');
});